<?php

include_once './base/HotPhpServerModel.php';

class moblienote_class extends HotPhpServerModel
{
    public $execFile = '';
    /**linkcheckreportd_class
     * 命令行提示信息
     *
     * @property string
     */
    protected $_usage = "\nUsage: [FILE] -f CONFIG_FILE [-q] \ncyclereportProc service\n";
    //服务初始化

    protected $ReportHandlers = null;

    public function init()
    {
        // 验证进程号文件
        if (isset($this->_config['pid_file']) == false) {
            echo "The configuration file is missing pid_file!\n";
            exit();
        }
        // 日志大小
        if (isset($this->_config['log_size']) == false) {
            echo "The configuration file is missing log_size!\n";
            exit();
        }

        //验证MYSQL数据库配置
        if (isset($this->_config['mysql_host']) == false) {
            echo "The configuration file is missing mysql_host!\n";
            exit;
        }
        if (isset($this->_config['mysql_port']) == false) {
            echo "The configuration file is missing mysql_port!\n";
            exit;
        }
        if (isset($this->_config['mysql_name']) == false) {
            echo "The configuration file is missing mysql_name!\n";
            exit;
        }
        if (isset($this->_config['mysql_user']) == false) {
            echo "The configuration file is missing mysql_user!\n";
            exit;
        }
        if (isset($this->_config['mysql_pass']) == false) {
            echo "The configuration file is missing mysql_pass!\n";
            exit;
        }
        //验证服务运行轮询间隔（秒）
        if (isset($this->_config['proc_interval']) == false) {
            echo "The configuration file is missing proc_interval!\n";
            exit;
        }

        //日志大小
        if (isset($this->_config['log_size']) == false) {
            echo "The configuration file is missing log_size!\n";
            exit;
        }
        // 设置运行间隔
        $this->setRunInterval($this->_config['proc_interval']);
        //$times = explode(',', $this->_config['proc_time']);
        // 初始化定时执行服务
        //$this->initTimingService($times);

        //当前有效日志条数初始化
        $this->setStatusValue('StartTime', 0); //服务启动的时间
        $this->setStatusValue('EndTime', 0);//服务结束的时间
        $this->setStatusValue('ServiceRunT',0);//服务运行时间
        $this->setStatusValue('WebFalse', 0);//无效的网站个数
        $this->setStatusValue('WebOverT', 0); //响应超时的网站个数
        $this->setStatusValue('LPageFalse', 0);//无效的着落页个数
        $this->setStatusValue('LPageOverT', 0);//响应超时的着落页个数
        $this->setStatusValue('LinkFalse', 0);//无效的短网址个数
        $this->setStatusValue('LinkOverT', 0);//响应超时的短网址个数
        $this->setStatusValue('DealAble', 0); //处理一个无效站点花的时间
    }

    //轮询服务入口方法
    public function service()
    {
        //设置服务启动时间
        //$this->setStatusValue('StartTime',0);
        //$this->setStatusValue('StartTime',microtime(true));
        $dsn = 'mysql:host=' . $this->_config['mysql_host'] . ';port=' . $this->_config['mysql_port'] . ';dbname=' . $this->_config['mysql_name'];
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        );
        //链接数据库
        try {
            $dbh = new PDO($dsn, $this->_config['mysql_user'], $this->_config['mysql_pass'], $options);
        } catch (PDOException $e) {
            //链接数据库失败
            $this->addLog(self::$LOG_LEVEL['CRIT'], __METHOD__ . "> Database link failure : " . $e->getMessage());
            return;
        }
        $strSQL = 'SELECT * FROM message_unsent_list WHERE  is_delete=0 ORDER BY create_time limit 0,1000';
        $result = $dbh->query($strSQL);
        if ($result === false) {
            //SQL执行失败，重新连接数据库
            $this->addLog(self::$LOG_LEVEL['ERR'], __METHOD__ . '> Get table ht_website_info error! SQL=' . $strSQL);
            //继续下次服务启动
            return;
        }
        $rows = $result->fetchAll();
        $truei = 0;
        $falsei = 0;
        $datarray = array();
        foreach ($rows as $value) {
            $datarray['template_id'] = $value['template_id'];
            $datarray['send_moblie'] = $value['send_moblie'];
            $datarray['send_content'] = $value['send_content'];
            $datarray['create_time'] = date('Y-m-d H:i:s',time());
            $results = $this->sendnote($datarray['send_moblie'],$datarray['send_content']);
            //echo($results);
            $resultss = 1;
            //等于1时 发送成功，删除待发送表中的数据，添加到已发送表中
            if($results=='"'.$resultss.'"'){
                $datarray['status_code'] = 1;
                $this->insertsentlist($value['unsent_id'],$datarray);
                $truei++;
            }else{
                $datarray['status_code'] = 0;
                $this->insertsentlist($value['unsent_id'],$datarray);
                $falsei++;
            }

        }
        $this->setStatusValue('LinkFalse',$truei);
        $this->setStatusValue('LinkOverT',$falsei);
        $this->setStatusValue('EndTime',0);
        $this->setStatusValue('EndTime',microtime(true));
        $this->setStatusValue('ServiceRunT',($this->getStatusValue('EndTime')-$this->getStatusValue('StartTime')));
        $this->setStatusValue('DealAble',($this->getStatusValue('WebFalse')+$this->getStatusValue('LPageFalse')+$this->getStatusValue('LinkFalse'))/($this->getStatusValue('EndTime')-$this->getStatusValue('StartTime')));
    }

    //定时服务入口方法
    public function timingService()
    {

    }


    //写入数据库
    public function  insertsentlist($unsent_id,$data=array()){
        //echo $unsent_id;
        $dsn = 'mysql:host=' . $this->_config['mysql_host'] . ';port=' . $this->_config['mysql_port'] . ';dbname=' . $this->_config['mysql_name'];
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        );
        //链接数据库
        try {
            $dbh = new PDO($dsn, $this->_config['mysql_user'], $this->_config['mysql_pass'], $options);
        } catch (PDOException $e) {
            //链接数据库失败
            $this->addLog(self::$LOG_LEVEL['CRIT'], __METHOD__ . "> Insertdata Database link failure : " . $e->getMessage());
            return;
        }
        //先删除待发送表里
        $strSQLDel = "DELETE FROM message_unsent_list WHERE unsent_id = $unsent_id";
        $Delresult = $dbh->query($strSQLDel);
        if ($Delresult === false) {
            //SQL执行失败，重新连接数据库
            $this->addLog(self::$LOG_LEVEL['ERR'], __METHOD__ . '> Get table ht_user_alert error! SQL=' . $strSQLDel);
            //继续下次服务启动
            return;
        }
        $template_id =$data['template_id'];
        $send_moblie =$data['send_moblie'];
        $send_content =$data['send_content'];
        $create_time =$data['create_time'];
        $status_code =$data['status_code'];
        $strSQL = "INSERT INTO message_sent_list (template_id,send_moblie,send_content,create_time,status_code) VALUES ($template_id,'".$send_moblie."','".$send_content."','".$create_time."',$status_code)";
        //echo $strSQL;
        //将数据插入事件表
        $result = $dbh->query($strSQL);
        if ($result === false) {
            //SQL执行失败，重新连接数据库
            $this->addLog(self::$LOG_LEVEL['ERR'], __METHOD__ . '> Get table ht_user_alert error! SQL=' . $strSQL);
            //继续下次服务启动
            return;
        }
    }

  //短信
    public  function sendnote($phone,$message){

        $params = array(
            "phone" => $phone,//
            "Message" => $message,//
        );
        try {
            $paramstring = http_build_query($params);
            $result = $this->juhecurl($this->_config['note_url'],$paramstring);

        }  catch (\Exception $ex) {
            $result['err_code'] = 40017;
            $result['err_msg'] = $ex->getMessage(); //  服务器错误
            return $result;
        }
        return $result;
    }

    function  juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        //   curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

}